'''
Created on Oct 27, 2009

@author: kage
'''

import os
import subprocess

class QueueItem():
    def __init__(self, inputUrl):
        self.inputUrl = inputUrl
        self.FileName = inputUrl.split('/')[len(inputUrl.split('/')) - 1]
        self.status = 'Ready'
        self.backgroundColor = 'white'
        self.outputUrl = None
        self.trackInfo = None
        self.__hasGeneralInfo = False
        self.__hasTrackInfo = False
        
        temp = self.FileName.split('.')
        if(len(temp) < 2):
            self.FileNameOnly = self.FileName
            self.ext = 'mkv'
        else:
            self.ext = temp[len(temp) - 1]
            self.FileNameOnly = self.FileName.replace('.' + self.ext, '')
    
    def resetStatus(self):
        self.status = 'Ready'
        self.backgroundColor = 'white'
        
    def setExt(self, ext):
        self.ext = ext
    
    def setOutputPath(self, outputFolder):
        self.outputUrl = os.path.join(str(outputFolder), str(self.FileNameOnly) + '.' + str(self.ext)).replace('\\', '/')
        
    def getGeneralInfo(self, args):
        if not self.__hasGeneralInfo:
            q = '"'
            self.generalInfo = {}
            self.__execute = q + args['mediaInfoPath'] + q + ' '
            self.__execute += q + '--Inform=file://' + args['templatePath'] + q + ' '
            self.__execute += q + self.inputUrl + q
            
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            self.__process = subprocess.Popen(str(self.__execute), stdout=subprocess.PIPE, startupinfo=startupinfo)
            self.__data = self.__process.communicate()[0]
            
            self.parseMediaInfoOutput(self.__data)
            
            #patching in case of incomplete data
            self.parseMediaInfoOutput('Format:-Unknown\nDuration:-00:00:00\nVideoID:-None\nAudioID:-None\nLanguage:-Unknown\n')
            self.__hasGeneralInfo = True
        return self.generalInfo
        
    def getTrackInfo(self, args):
        if not self.__hasTrackInfo:
            q = '"'
            self.__execute = q + args['mediaInfoPath'] + q + ' '
            self.__execute += q + self.inputUrl + q
            
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            self.__process = subprocess.Popen(str(self.__execute), stdout=subprocess.PIPE, startupinfo=startupinfo)
            temp = self.__process.communicate()[0]
            
            #processing required data
            processed = ''
            flag = 0
            for line in temp.split('\n'):
                if line == 'Video\r' or line == 'Audio\r' or line == 'Video' or line == 'Audio':
                    flag = 1
                if flag == 1:
                    try:
                        ind = line.find(':')
                        outline = line[:ind].strip() + line[ind:].strip()
                    except:
                        outline = line
                        
                    processed += outline + '\n'
                else:
                    flag = 0
            
            self.trackInfo = processed
            self.__hasTrackInfo = True
        return self.trackInfo
        
    def parseMediaInfoOutput(self, data):
        for line in data.split('\n'):
            if line != '\r' and line != '':
                props = line.split(":-")
                if props[0] not in self.generalInfo.keys():
                    self.generalInfo[props[0]] = props[1]
        
            
        
